package com.kaibes.web.util;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.PathResource;
import org.springframework.core.io.Resource;

public class ResourceUtils {
    
    private static final String CLASSPATH_URL_PREFIX = "classpath:";
    private static final String FILE_URL_PREFIX = "file:";
    private static final String TEMPLATES = "templates/";
    private static final String STATIC = "static/";

    public static Resource findResource(String uri) {
        if (uri.startsWith(FILE_URL_PREFIX)) {
            uri = uri.substring(FILE_URL_PREFIX.length());
            return new PathResource(uri);
        } else if (uri.startsWith(CLASSPATH_URL_PREFIX)) {
            uri = uri.substring(CLASSPATH_URL_PREFIX.length());
            return new ClassPathResource(uri);
        } else {
            Resource resource = new PathResource(TEMPLATES + uri);
            boolean flag = resource.exists();
            if (!flag) {
                resource = new ClassPathResource(TEMPLATES + uri);
                flag = resource.exists();
                if (!flag) {
                    resource = new ClassPathResource(STATIC + uri);
                    flag = resource.exists();
                }
            }
            if (flag) {
                return resource;
            } else {
                return null;
            }
        }
    }
}
